#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper



node (params.nodeLabel) {
    def status = 0
    def tomcatHome = '/home/tomcat'
    def tomcatWebPath = tomcatHome + '/webapps'
    def bakPath = '/opt/app-bak'
    println(params.action)
    if('start' == params.action){
        actionStartTomcat(tomcatHome)
    }else {
        println('No Action Not Found...')
    }
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${params.nodeLabel}",timeout: 10)
        println('Status: '+response.status)
    }
}

def startTomcat(tomcatHome){
    println("---- startTomcat ----:"+tomcatHome)
    script{
        withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
            sh """
            ${tomcatHome}/bin/startup.sh
          """
        }
    }
}

def copyWarToTomcat(tomcatWebPath){
    println("---- COPY ----:"+tomcatWebPath)
    sh """
    cp ${params.packageName}.${params.packageType} ${tomcatWebPath}
    """
}

def actionStartTomcat(tomcatHome){
    stage('Start App'){
        try{
            stage('Start App'){
                startTomcat(tomcatHome)
                sleep 20
            }
            stage('Verify Tomcat'){
                def resp = httpRequest("http://localhost:${params.appPort}")
                println('Status: '+resp.status)
            }
            stage('Verify App'){
                def resp = httpRequest("http://localhost:${params.appPort}${params.appCheckUrl}")
                println('Status: '+resp.status)
            }
            notifyDeployCentral(16001)
        }catch (e){
            echo 'Start App Error !'
            notifyDeployCentral(16002)
            throw e
        }
    }
}
